package web.Courts;

import com.google.gson.Gson;
import entity.CourtsBean;
import entity.MemberBean;
import entity.OrdersBean;
import services.CourtsServiceAll;
import services.MemberServices;
import services.OrdersService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;

@WebServlet("/doSettle")
public class DoSettle extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        String courtId = req.getParameter("court_id");
        int total_amount = Integer.parseInt(req.getParameter("total_amount"));
        int order_id = new OrdersService().getOrderByCourt_id(Integer.parseInt(courtId)).getOrder_id();
        Timestamp now = Timestamp.valueOf(LocalDateTime.now(ZoneId.systemDefault()));
        int num = 0;
        String isMember = req.getParameter("memberId");
        MemberBean memberById = null;
        if(!"1".equals(isMember)){
            // 是会员需要查看该会员的余额够不够
            memberById = new MemberServices().getMemberId(Integer.parseInt(isMember));
            if(memberById.getBalance().compareTo(new BigDecimal(total_amount)) < 0){
                //余额不足
                resp.getWriter().println("{\"msg\":\"该会员余额不足\",\"msgType\":\"warning\"}");
                return;
            }
        }
        // 把余额减掉
        BigDecimal subtract = memberById.getBalance().subtract(new BigDecimal(total_amount));
        // 先将对应订单编号的的关台时间加上
        num = new OrdersService().doSettle(order_id, now,total_amount);
        // 重新设置该会员的余额
        new MemberServices().conSumption(subtract,new BigDecimal(total_amount),memberById.getMember_id());
        // 再将球桌恢复
        new CourtsServiceAll().restoreCourtsByCourId(Integer.parseInt(courtId));
        Gson gson = new Gson();
        resp.getWriter().println(num > 0?"{\"msg\":\"结算成功\",\"msgType\":\"success\"}":"{\"msg\":\"结算失败\",\"msgType\":\"danger\"}");
    }
}
